from infra.handler import BaseHandler
from common.log import logInfo
from common.tencent_miniprogram_api import login_wechat_backend
from common.jwt import create_jwt_token
from common.log import logInfo
from .girls_db import update_girls_info
from .girls_db import check_user_info
from .girls_db import create_new_user
from .girls_db import get_user_info_by_wechat_id
from .girls_db import get_user_by_id

import json
class GirlsHandler(BaseHandler):
    async def get(self):
        """
        获取girls的信息
        """
        try:
            union_id, _ = self.get_current_user()
            if not union_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            # 获取请求参数中的user_id
            user_id = self.get_argument('user_id', None)
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User ID is required"}))
                return

            # 调用数据库方法获取用户信息
            success, user_info = await get_user_by_id(user_id)
            print("user_info:", user_id)
            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "success",
                    "data": user_info
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": "Failed to get user info",
                    "data": None
                }))
                
        except Exception as e:
            self.write(json.dumps({"code": 404, "msg": str(e)}))
    async def put(self):
        """
        修改girls的信息
        """
        try:
            union_id, _ = self.get_current_user()
            print("union_id:", union_id)
            if not union_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                # logInfo(admin_id, "", account_type, "User not found")
                return
            # Get the JSON body from the request
            # print("body:", self.request.body)
            body = json.loads(self.request.body)
            print("body:", body)
            required_fields = ["name", "phone_number", "age", "profession", "city", "interests", "is_auth", "photo_url","mask_info"]
            for field in body:
                if field not in required_fields or not body[field]:
                    self.write(json.dumps({"code": 404, "msg": f"{field} not in required_fields"}))
                    # logInfo(admin_id, "", account_type, f"{field} not in required_fields")
                    return 
            success, result = await update_girls_info(union_id, body)
            if success:
                self.write(json.dumps({"code": 200, "msg": f"Updated girls record with ID {union_id}"}))
                # logInfo(admin_id, "", account_type, "update doctor success")
            else:
                self.write(json.dumps({"code": 404, "msg": f"Failed to update doctor record: {result}"}))
                # logInfo(admin_id, "", account_type, "update doctor failed")
        except json.JSONDecodeError:
            self.write(json.dumps({"code": 404, "msg": "Invalid JSON format in the request body"}))
            # logInfo(admin_id, "", account_type, "Invalid JSON format in the request body")
        except Exception as e:
            self.write(json.dumps({"code": 404, "msg": str(e)}))
            # logInfo(admin_id, "", account_type, str(e))


class LoginHandler(BaseHandler):
    async def post(self):
        try:
            data = json.loads(self.request.body.decode())
            code = data.get("code")
            # 1. 登录微信服务器验证code
            result, res_data = await login_wechat_backend(code)
            if result:
                # 2. 登录成功，返回用户信息
                openid = res_data["openid"]
                # 3. 检查用户信息是否存在，如果不存在在系统中创建，如果存在则直接返回用户信息
                if not await check_user_info(openid):
                    ret, id =  await create_new_user(openid)
                    token = create_jwt_token(id,0,0)
                    if not ret:
                        self.write(json.dumps({"code":404,"msg":"创建用户失败"}))
                        # logInfo(res_data["id"], res_data["phonenumber"], res_data["account_type"], "创建用户失败")
                    else:
                        self.write(json.dumps({"code":200,"msg":{"wechat_id":openid, "token":token, points:10}}))  
                else:
                    ret, user_info = await get_user_info_by_wechat_id(openid)
                    token = create_jwt_token(user_info['id'], user_info['phone_number'],0)
                    if not ret:
                        self.write(json.dumps({"code":404,"msg":"获取用户信息失败"}))
                        # logInfo(res_data["id"], res_data["phonenumber"], res_data["account_type"], "获取用户信息失败")
                    else:
                        user_info["token"] = token
                        self.write(json.dumps({"code":200,"msg":user_info}))          
                    # logInfo(res_data["id"], res_data["phonenumber"], res_data["account_type"], "登录成功")  
            else:
                # 3. 登录失败，返回错误信息
                self.write(json.dumps({"code":404,"msg":res_data}))
                # logInfo(res_data["id"], res_data["phonenumber"], res_data["account_type"], "登录失败")

        except json.JSONDecodeError:
            self.write(json.dumps({"code":404,"msg":"Invalid JSON data"}))
            # logInfo(id, phonenumber, account_type, "Invalid JSON data")
        except Exception as e:
            self.write(json.dumps({"code":404,"msg":f"An error occurred: {str(e)}"}))
            # logInfo(id, phonenumber, account_type, f"An error occurred: {str(e)}")
